package com.zztl.infiniteBand.ui.view

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.zztl.infiniteBand.R


/**
 * Project:WebViewProgressBar
 * Author:dyping
 * Date:2017/7/24 13:58
 */

class WebProgressBarView : View {

    lateinit var  mContext: Context
    private var mCurProgress: Int = 0
    private var mWidth: Int = 0
    private var mHeight: Int=0
    lateinit var mPaint: Paint
    private var mColor: Int=0
    private val endListener: EventEndListener? = null


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

        mContext = context
        val array = context.obtainStyledAttributes(attrs, R.styleable.appProgress)
        mCurProgress = array.getInt(R.styleable.appProgress_progress, 0)
        mHeight = array.getInt(R.styleable.appProgress_progressHeight, 200)
        mColor = array.getColor(R.styleable.appProgress_progressColor, Color.parseColor("#00FFEA"))
        array.recycle()

        mPaint = Paint()
        mPaint.color = mColor
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mWidth = View.MeasureSpec.getSize(widthMeasureSpec)
    }


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val result = mWidth * (mCurProgress.toFloat() / 100.toFloat())
        canvas.drawRect(0f, 0f, result, mHeight.toFloat(), mPaint)
    }

    fun setCurProgress(time: Long, endListener: EventEndListener?) {
        val animator = ValueAnimator.ofInt(mCurProgress, 100)
        animator.duration = time
        animator.addUpdateListener { animation -> setNormalProgress(animation.animatedValue as Int) }

        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {

            }

            override fun onAnimationEnd(animation: Animator) {
                endListener?.onEndEvent()
            }

            override fun onAnimationCancel(animation: Animator) {

            }

            override fun onAnimationRepeat(animation: Animator) {

            }
        })

        animator.start()

    }

    fun setNormalProgress(mCurProgress: Int) {
        this.mCurProgress = mCurProgress
        postInvalidate()
    }


    interface EventEndListener {
        fun onEndEvent()
    }

}
